// src/controller/user.ts

import { Body, Controller, Inject, Post, Query } from '@midwayjs/decorator';
import { User } from '../../interface';
import { Context } from '@midwayjs/koa';

@Controller('/api/controller/param/body')
export class UserController {
  @Inject()
  ctx: Context;

  /**
   * 示例：获取单个 body
   * // src/controller/user.ts
   * // POST /user/ HTTP/1.1
   * // Host: localhost:3000
   * // Content-Type: application/json; charset=UTF-8
   * //
   * // {"uid": "1", "name": "harry"}
   */
  @Post('/getBodySingle')
  async getBodySingle(@Body('uid') uid: string): Promise<User> {
    // id 等价于 ctx.request.body.uid
    console.log('uid:', uid);
    return {
      id: 1,
      name: 'testAtQuery',
      age: 1,
    };
  }

  /**
   * 示例：获取整个 body
   * // src/controller/user.ts
   * // POST /user/ HTTP/1.1
   * // Host: localhost:3000
   * // Content-Type: application/json; charset=UTF-8
   * //
   * // {"uid": "1", "name": "harry"}
   */
  @Post('/getBodyFull')
  async getBodyFull(@Body() user: User): Promise<User> {
    // user 等价于 ctx.request.body 整个 body 对象
    // => output user
    // {
    //   uid: '1',
    //   name: 'harry',
    // }
    console.info('user:', user);
    return {
      id: 1,
      name: 'testAtQuery',
      age: 1,
    };
  }

  /**
   * 示例：从 API 获取 body
   * // src/controller/user.ts
   * // POST /user/ HTTP/1.1
   * // Host: localhost:3000
   * // Content-Type: application/json; charset=UTF-8
   * //
   * // {"uid": "1", "name": "harry"}
   */
  @Post('/getBodyFromApi')
  async getBodyFromApi(): Promise<User> {
    const body = this.ctx.request.body;
    // {
    //   uid: '1',
    //   name: 'harry',
    // }
    console.log('body:', body);
    return {
      id: 1,
      name: 'testAtQuery',
      age: 1,
    };
  }

  /**
   * 示例：获取 query 和 body 参数
   */
  @Post('/getQueryParamAndBodySameTime')
  async getQueryParamAndBodySameTime(
    @Body() user: User,
    @Query('pageIdx') pageIdx: number
  ): Promise<User> {
    // user 从 body 获取
    // pageIdx 从 query 获取
    console.info('user:', user);
    console.info('pageIdx:', pageIdx);
    return {
      id: 1,
      name: 'testAtQuery',
      age: 1,
    };
  }
}
